package com.mdc.mansion.web.modules.basedata.web;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.mdc.mansion.common.util.SerialToolKit;
import com.mdc.mansion.core.modules.basedata.QrcodeUseLogService;
import com.mdc.mansion.core.modules.basedata.TableQrCodeService;
import com.mdc.mansion.core.modules.basedata.dto.AppConfigDTO;
import com.mdc.mansion.core.modules.restaurant.RestaurantTableService;
import com.mdc.mansion.core.modules.system.SysDictService;
import com.mdc.mansion.dataaccess.common.persistence.Page;
import com.mdc.mansion.dataaccess.modules.basedata.entity.QrcodeUseLog;
import com.mdc.mansion.dataaccess.modules.basedata.entity.TableQrCode;
import com.mdc.mansion.dataaccess.modules.system.entity.Dict;
import com.mdc.mansion.dataaccess.modules.system.entity.User;
import com.mdc.mansion.web.common.web.BaseController;
import com.mdc.mansion.web.modules.system.utils.UserUtils;

/**
 * 餐桌二维码信息Controller
 * 
 * @author mingdongc
 * @version 2018-01-01
 */
@Controller
@RequestMapping(value = "${adminPath}/basedata/tableQrCode")
public class TableQrCodeController extends BaseController {

    @Autowired
    private TableQrCodeService tableQrCodeService;
    @Autowired
    private SysDictService sysDictService;
    
    @Autowired
    private QrcodeUseLogService qrcodeUseLogService;
    
    @ModelAttribute
    public TableQrCode get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return tableQrCodeService.get(id);
        } else {
            return new TableQrCode();
        }
    }

    @RequiresPermissions("basedata:tableQrCode:view")
    @RequestMapping(value = { "list", "" })
    public ModelAndView list(TableQrCode tableQrCode) {
        Map<String, Object> model = new HashMap<String, Object>();
        Page<TableQrCode> page = tableQrCodeService.findPage(tableQrCode);
        model.put("page", page);
        ModelAndView modelAndView = new ModelAndView("modules/basedata/tableQrCodeList", model);
        return modelAndView;
    }

    @RequiresPermissions("basedata:tableQrCode:view")
    @RequestMapping(value = "form")
    public ModelAndView form(TableQrCode tableQrCode) {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("tableQrCode", tableQrCode);
        return new ModelAndView("modules/basedata/tableQrCodeForm", model);
    }
    @RequiresPermissions("basedata:tableQrCode:edit")
    @RequestMapping(value = "save")
    public ModelAndView save(TableQrCode tableQrCode, RedirectAttributes redirectAttributes) {
        User u = UserUtils.getUser();
        tableQrCode.setUpdateBy(u);
        if (StringUtils.isNotBlank(tableQrCode.getId())) {
            tableQrCodeService.updateSelective(tableQrCode);
        } else {
            tableQrCode.setCreateBy(u);
            tableQrCodeService.save(tableQrCode);
        }
        this.addMessage(redirectAttributes, "操作成功");
        return new ModelAndView("redirect:./list");
    }

    @RequiresPermissions("basedata:tableQrCode:edit")
    @RequestMapping(value = "delete")
    public ModelAndView delete(TableQrCode tableQrCode, RedirectAttributes redirectAttributes) {
        tableQrCodeService.delete(tableQrCode);
        this.addMessage(redirectAttributes, "操作成功");
        return new ModelAndView("redirect:./list");
    }
    
    @RequiresPermissions("basedata:tableQrCode:edit")
    @RequestMapping(value = "initCreateQrCode")
    public ModelAndView initCreateQrCode(TableQrCode tableQrCode, RedirectAttributes redirectAttributes) {
        Map<String, Object> model = new HashMap<String, Object>();
        ModelAndView modelAndView = new ModelAndView("modules/basedata/tableQrCodeCreate", model);
        return modelAndView;
    }
    @RequiresPermissions("basedata:tableQrCode:edit")
    @RequestMapping(value = {"batchCreate"})
    public void batchCreate(HttpServletRequest request,HttpServletResponse response,Integer length) throws Exception {
        if(length == null || length == 0){
            return;
        }
        byte[] buf = new byte[1024];    
        List<TableQrCode> qrCodeUrlList = new ArrayList<>();
        String host = tableQrCodeService.getQrHost();
        for(int i = 1;i<=length;i++){
            String codeSign = SerialToolKit.id();
            TableQrCode tableQrCode = new TableQrCode();
            String url = host+"/api"+ tableQrCodeService.createQrCodeUrl(codeSign);
            tableQrCode.setCodeSign(codeSign);
            tableQrCode.setUrl(url);
            tableQrCode.setCodeStatus(0);
            qrCodeUrlList.add(tableQrCode);
            
            /****2018年4月9日 22:00:30 增加对批量生成二维码记录,并在绑定的时候进行数据更新***/
            User u = UserUtils.getUser();
            QrcodeUseLog qrcodeUseLog = new QrcodeUseLog();
            qrcodeUseLog.setCodeSign(codeSign);
            qrcodeUseLog.setCodeUrl(url);
            qrcodeUseLog.setQrcodeStatus(QrcodeUseLog.QRCODE_STATUS.UNUSED.getVal());
            qrcodeUseLog.setCreateTime(Calendar.getInstance().getTime());
            qrcodeUseLog.setCreateBy(u);
            qrcodeUseLogService.save(qrcodeUseLog);
            
        }
        List<BufferedImage> imgList = tableQrCodeService.batchCreateQrCode(qrCodeUrlList);
        OutputStream out = response.getOutputStream();
        ZipOutputStream zipOut = new ZipOutputStream(out);
        for(int i = 0,j = imgList.size();i<j;i++){
            zipOut.putNextEntry(new ZipEntry("img_"+i+".png"));
            BufferedImage bi = imgList.get(i);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
            ImageIO.write(bi, "png", imageOutput);
            InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            int len;    
            while ((len = inputStream.read(buf)) > 0) {    
                zipOut.write(buf, 0, len);    
            }    
            // Complete the entry    
            zipOut.closeEntry();    
            inputStream.close();    
        }
        zipOut.flush();
        out.flush();
        zipOut.close();
        out.close();
    }
    @RequiresPermissions("basedata:tableQrCode:edit")
    @RequestMapping(value = "exportById")
    public void exportById(HttpServletRequest request,HttpServletResponse response,String id) throws Exception {
        TableQrCode tableQrCode = tableQrCodeService.get(id);
        BufferedImage img = tableQrCodeService.createImgQrCode(tableQrCode);
        OutputStream out = response.getOutputStream();
        response.setContentType("application/png");
        response.setHeader("Content-Disposition", "attachment; filename=\""
                + "qrCode"+id+".png");
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
        ImageIO.write(img, "png", imageOutput);
        InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        byte[] buf = new byte[1024];   
        int len;    
        while ((len = inputStream.read(buf)) > 0) {    
            out.write(buf, 0, len);    
        } 
        inputStream.close();
        out.flush();
        out.close();
    }
    
    @RequiresPermissions("basedata:tableQrCode:view")
    @RequestMapping(value = "exportByCodeSign")
    public void exportByCodeSign(HttpServletRequest request,HttpServletResponse response,String qrCodeSign) throws Exception {
    	TableQrCode inputCode = new TableQrCode();
    	inputCode.setCodeSign(qrCodeSign);
    	List<TableQrCode> tableQrCodeList = tableQrCodeService.findList(inputCode);
    	if(!(null == tableQrCodeList || 0 == tableQrCodeList.size()))
    	{
    		TableQrCode tableQrCode = tableQrCodeList.get(0);
    		BufferedImage img = tableQrCodeService.createImgQrCode(tableQrCode);
            OutputStream out = response.getOutputStream();
            response.setContentType("application/png");
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + "qrCode"+tableQrCode.getId()+".png");
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
            ImageIO.write(img, "png", imageOutput);
            InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            byte[] buf = new byte[1024];   
            int len;    
            while ((len = inputStream.read(buf)) > 0) {    
                out.write(buf, 0, len);    
            } 
            inputStream.close();
            out.flush();
            out.close();
    	}
        
    }
    
}
